//
//  Helper.m
//  PalmKitchen
//
//  Created by apple on 14-10-14.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "Helper.h"
#import <AssetsLibrary/AssetsLibrary.h>
@implementation Helper

+(UIButton *)createButton:(CGRect)frame title:(NSString *)title image:(UIImage *)image target:(id)target selector:(SEL)selector
{
    UIButton * button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    button.frame=frame;
    CGRect newFrame=frame;
    newFrame.origin.y=frame.size.height/2.0;
    newFrame.size.height=frame.size.height/2.0;
    newFrame.origin.x=0;
    UILabel * label=[[UILabel alloc]initWithFrame:newFrame];
    label.text=title;
    [button addSubview:label];
    label.font=[UIFont systemFontOfSize:12];
    label.backgroundColor=[UIColor clearColor];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    return button;
}
+(NSMutableAttributedString *)getAttributedStringWith:(NSString *)string andDic:(NSDictionary<NSAttributedStringKey, id> *)AttrDic range:(NSRange)range;{
    
    NSMutableAttributedString *str=[[NSMutableAttributedString alloc]initWithString:string];
    [str addAttributes:AttrDic range:range];
    //@{NSForegroundColorAttributeName:UIColorFromRGB(0X999999),NSFontAttributeName:Font_Regular(13)}
    
    return str;
}
+(CGSize)sizeLabelWidth:(CGFloat)width andLines:(int )index andFont:(UIFont *)font attributedText:(NSAttributedString *)attributted
{
    if(width<=0){
        return CGSizeZero;
    }
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 1000)];
    lab.attributedText = attributted;
    lab.numberOfLines = index;
    lab.font=font;
    CGSize labSize = [lab sizeThatFits:lab.bounds.size];
    return labSize;
}
+(CGRect)getTextFrameWithText:(NSString *)strContext withSize:(CGSize)size withFont:(UIFont *)font{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    [dic setValue:font forKey:NSFontAttributeName];//@{NSFontAttributeName: font}
    
    //    NSDictionary * dict=[NSDictionary dictionaryWithObject:[UIFont boldSystemFontOfSize:15]  forKey:NSFontAttributeName];
    CGRect rect=[strContext boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)  attributes:dic  context:nil];
    
    return rect;
}
+(CGRect)getTextFrameWithText:(NSString *)strContext withSize:(CGSize)size LabelSpeace:(CGFloat)lineSpeace withFont:(UIFont*)font; {
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpeace];
    paragraphStyle.lineSpacing = lineSpeace;
    [dic setValue:font forKey:NSFontAttributeName];
    [dic setValue:paragraphStyle forKey:NSParagraphStyleAttributeName];
    CGRect rect=[strContext boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)  attributes:dic context:nil];
    return rect;
}
+(UIImage *)compressImageWith:(UIImage *)image
{
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = 640;
    float height = image.size.height/(image.size.width/width);
    
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }
    
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

+(CGFloat)widthOfString:(NSString *)string font:(UIFont *)font height:(CGFloat)height
{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    [dic setValue:font forKey:NSFontAttributeName];
    
    CGRect rect=[string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.width;
}

+(CGFloat)heightOfString:(NSString *)string font:(UIFont *)font width:(CGFloat)width
{
    CGRect bounds;
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    [dic setValue:font forKey:NSFontAttributeName];
    bounds=[string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return bounds.size.height;
}
+(CGFloat)heightWithfont:(int)font;{
    CGRect bounds;
    NSString *string=@"我";
    NSDictionary * parameterDict=[NSDictionary dictionaryWithObject:Font_Regular(font) forKey:NSFontAttributeName];
    bounds=[string boundingRectWithSize:CGSizeMake(100, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:parameterDict context:nil];
    return bounds.size.height;
    
}
+(CGFloat)heightWithNum:(int)index font:(int)font;{
    CGRect bounds;
    NSMutableString *string=[[NSMutableString alloc]init];
    
    for (int i=0; i<index; i++) {
        if (i==0) {
            [string appendString:@"我"];
        }else{
            [string appendString:@"\n我"];
        }
        
    }
    
    NSDictionary * parameterDict=[NSDictionary dictionaryWithObject:Font_Regular(font) forKey:NSFontAttributeName];
    bounds=[string boundingRectWithSize:CGSizeMake(100, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:parameterDict context:nil];
    return bounds.size.height;
    
}
+(CGRect )getWidthWithString:(NSString* )string with:(UIFont *)font;
{
    
    CGRect strSize=[Helper getTextFrameWithText:string withSize:CGSizeMake(400, 44) withFont:font];
    
    
    return strSize;
}
+(CGRect )getWidthWith:(int )index with:(UIFont *)font{
    NSMutableString *str=[[NSMutableString alloc]init];
    for (int i=1; i<=index; i++) {
        [str appendString:@"题"];
    }
    CGRect strSize=[Helper getTextFrameWithText:str withSize:CGSizeMake(400, 44) withFont:font];
    
    
    return strSize;
}
#pragma  mark - 获取当天的日期：年月日
+ (NSDictionary *)getTodayDate
{
    
    //获取今天的日期
    NSDate *today = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit = kCFCalendarUnitYear|kCFCalendarUnitMonth|kCFCalendarUnitDay;
    
    NSDateComponents *components = [calendar components:unit fromDate:today];
    NSString *year = [NSString stringWithFormat:@"%ld", [components year]];
    NSString *month = [NSString stringWithFormat:@"%02ld", [components month]];
    NSString *day = [NSString stringWithFormat:@"%02ld", [components day]];
    
    NSMutableDictionary *todayDic = [[NSMutableDictionary alloc] init];
    [todayDic setObject:year forKey:@"year"];
    [todayDic setObject:month forKey:@"month"];
    [todayDic setObject:day forKey:@"day"];
    
    return todayDic;
    
}
//邮箱
+ (BOOL) justEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}


//手机号码验证
+ (BOOL) justMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(17[0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
//手机号码验证
+ (BOOL)validateMobile:(NSString *)mobileNum
{
    mobileNum = [mobileNum stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobileNum.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobileNum];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobileNum];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobileNum];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

//车牌号验证
+ (BOOL) justCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    WWLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}


//车型
+ (BOOL) justCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}


//用户名
+ (BOOL) justUserName:(NSString *)name
{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}
//11111
+ (BOOL) justTextIsInt:(NSString *)str
{
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}



//密码
+ (BOOL) justPassword:(NSString *)passWord
{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,12}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}


//昵称
+ (BOOL) justNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}


//身份证号
+ (BOOL) justIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}
+ (BOOL) isEmpty:(NSString *) str {
    
    if (!str) {
        return true;
    } else {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return false;
        } else {
            return true;
        }
    }
}

//获取字符串首字母(传入汉字字符串, 返回大写拼音首字母)
+(NSString *)getFirstLetterFromString:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为xiao写拼音
    NSString *strPinYin = [str lowercaseString];
    //获取并返回首字母
    return [strPinYin substringToIndex:1];
}
+(UIImage *)convertViewToImage
{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];
    UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return capturedScreen;
}

+(UIImage *)getShearImageViewToImage:(CGRect)frame image:(NSString*)imgStr;
{
    //    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    //    CGRect rect = [keyWindow bounds];
    UIImageView *imageView=[[UIImageView alloc]init];
    imageView.frame=CGRectMake(0, 0, frame.size.width, frame.size.height+1);
    imageView.backgroundColor=UIColorFromRGB(0Xf0f0f0);
    imageView.contentMode=UIViewContentModeCenter;
    imageView.image=[UIImage imageNamed:imgStr];
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageView.frame.size.width, imageView.frame.size.height-1),YES,0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [imageView.layer renderInContext:context];
    UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return capturedScreen;
}

+(UIImage *)creatImageFromColor:(UIColor *)color with:(CGSize)mySize{
    
    //    CGFloat W=[UIScreen mainScreen].bounds.size.width;
    //    CGFloat H=[UIScreen mainScreen].bounds.size.height;
    
    CGFloat W=mySize.width;
    CGFloat H=mySize.height;
    
    CGRect rect = CGRectMake(0, 0, W, H);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
+(UIImage *)resizebleImageWithString:(NSString *)imgStr;{
    
    UIImage *newImg=[UIImage imageNamed:imgStr];
    CGFloat w=newImg.size.width;
    CGFloat h=newImg.size.height;
    
    newImg=[newImg resizableImageWithCapInsets:UIEdgeInsetsMake(w*0.5, h*0.5, w*0.5, h*0.5) resizingMode:UIImageResizingModeStretch];
    return newImg;
}
+(UIImage *)resizebleImageWithImage:(UIImage *)newImg;{
    
    CGFloat w=newImg.size.width;
    CGFloat h=newImg.size.height;
    
    newImg=[newImg resizableImageWithCapInsets:UIEdgeInsetsMake(w*0.5, h*0.5, w*0.5, h*0.5) resizingMode:UIImageResizingModeStretch];
    return newImg;
}
/**
 *  压缩图片到指定尺寸大小
 *
 *  @param image 原始图片
 *  @param size  目标大小
 *
 *  @return 生成图片
 */
+(UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
    UIImage * resultImage = image;
    UIGraphicsBeginImageContext(size);
    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIGraphicsEndImageContext();
    return resultImage;
}

//图片缩放到指定大小尺寸
+(UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    //    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    
    
    return img;
}
//键盘上面加完成
+(UIToolbar *)addToolbar
{
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(10, 0, WIDTH, 35)];
    toolbar.tintColor = [UIColor blackColor];
    toolbar.backgroundColor = [UIColor grayColor];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(textFieldShouldReturn:)];
    toolbar.items = @[space, bar];
    return toolbar;
}
+ (NSArray *)readQRCodeFromImage:(UIImage *)image{
    // 创建一个CIImage对象
    CIImage *ciImage = [[CIImage alloc] initWithCGImage:image.CGImage options:nil];
    CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer : @(YES)}]; // 软件渲染
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh}];// 二维码识别
    // 注意这里的CIDetectorTypeQRCode
    NSArray *features = [detector featuresInImage:ciImage];
    
    return features;
}
//处理乱码
+(NSString *)ToDealWithCode:(NSString *)string;{
    NSString *resultStr=nil;
    NSData *data=[string dataUsingEncoding:NSUTF8StringEncoding];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];//如果中文是utf-8编码转gbk结果为空(还没搞明白)
    if (retStr)//如果扫描中文乱码则需要处理，否则不处理
    {
        NSInteger max = [string length];
        char *nbytes = malloc(max + 1);
        for (int i=0; i<max; i++) {
            unichar ch = [string  characterAtIndex: i];
            nbytes[i] = (char) ch;
        }
        
        nbytes[max] = '\0';
        resultStr=[NSString stringWithCString: nbytes
                                     encoding: enc];
    }
    
    return resultStr;
}
/*
 +(UIImage *)getScaleToSize:(UIImage *)img size:(CGSize)size;{
 
 // 创建一个bitmap的context
 CGSize newSize;
 
 
 //被切图片宽比例比高比例小 或者相等，以图片宽进行放大
 if (img.size.width*size.height <= img.size.height*size.width) {
 
 //以被剪裁图片的宽度为基准，得到剪切范围的大小
 //        CGFloat width  = img.size.width;
 //        CGFloat height = img.size.width * size.height / size.width;
 CGFloat  H;
 H=img.size.height*size.width/img.size.width;
 
 newSize=CGSizeMake(size.width, H);
 
 }else{ //被切图片宽比例比高比例大，以图片高进行剪裁
 
 // 以被剪切图片的高度为基准，得到剪切范围的大小
 //        CGFloat width  = img.size.height * size.width / size.height;
 //        CGFloat height = img.size.height;
 
 CGFloat  W;
 W=img.size.width *size.height/img.size.height;
 
 newSize=CGSizeMake(W, size.height);
 
 }
 
 
 // 并把它设置成为当前正在使用的context
 UIGraphicsBeginImageContext(newSize);
 // 绘制改变大小的图片
 
 [img drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
 // 从当前context中创建一个改变大小后的图片
 UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
 // 使当前的context出堆栈
 UIGraphicsEndImageContext();
 // 返回新的改变大小后的图片
 return scaledImage;
 
 }
 */
+(UIImage *)getScaleToSize:(UIImage *)img size:(CGSize)size;{
    
    // 创建一个bitmap的context
    CGSize newSize;
    CGFloat  W=img.size.width *size.height/img.size.height;
    
    newSize=CGSizeMake(W, size.height);
    
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(newSize);
    // 绘制改变大小的图片
    
    [img drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
    
}
+(UIImage *)clipImage:(UIImage *)image toRect:(CGSize)size;{
    
    //被切图片宽比例比高比例小 或者相等，以图片宽进行放大
    if (image.size.width*size.height <= image.size.height*size.width) {
        
        //以被剪裁图片的宽度为基准，得到剪切范围的大小
        CGFloat width  = image.size.width;
        CGFloat height = image.size.width * size.height / size.width;
        
        // 调用剪切方法
        // 这里是以中心位置剪切，也可以通过改变rect的x、y值调整剪切位置
        return [self imageFromImage:image inRect:CGRectMake(0, (image.size.height -height)/2, width, height)];
        
    }else{ //被切图片宽比例比高比例大，以图片高进行剪裁
        
        // 以被剪切图片的高度为基准，得到剪切范围的大小
        CGFloat width  = image.size.height * size.width / size.height;
        CGFloat height = image.size.height;
        
        // 调用剪切方法
        // 这里是以中心位置剪切，也可以通过改变rect的x、y值调整剪切位置
        return [self imageFromImage:image inRect:CGRectMake((image.size.width -width)/2, 0, width, height)];
    }
    return nil;
}
+(UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect{
    
    //将UIImage转换成CGImageRef
    CGImageRef sourceImageRef = [image CGImage];
    
    //按照给定的矩形区域进行剪裁
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
    
    //将CGImageRef转换成UIImage
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    
    //返回剪裁后的图片
    return newImage;
}
/**
 *  重新绘制图片
 *
 *  @param color 填充色
 *
 *  @return UIImage
 */
+(UIImage *)imageChange:(UIImage *)image WithColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    CGContextClipToMask(context, rect, image.CGImage);
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
/** 打开手电筒 */
+ (void)openFlashlight {
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    if ([captureDevice hasTorch]) {
        BOOL locked = [captureDevice lockForConfiguration:&error];
        if (locked) {
            captureDevice.torchMode = AVCaptureTorchModeOn;
            [captureDevice unlockForConfiguration];
        }
    }
}
/** 关闭手电筒 */
+ (void)closeFlashlight {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode: AVCaptureTorchModeOff];
        [device unlockForConfiguration];
    }
}
+(void)palySoundName:(int)nameNum{
    
    //播放系统提示音
    
    SystemSoundID soundIDTest = nameNum;
    AudioServicesPlaySystemSound(soundIDTest);
    
}
/*小数点后两位，或整数 */
+(NSString *)getNewStringWith:(NSString *)str;{
    
    NSString *string;
    NSArray *arr=[str componentsSeparatedByString:@"."];
    if (arr.count==2) {
        NSString *lastStr=[arr lastObject];
        if (lastStr.length>2) {
            
            NSString *last=[NSString stringWithFormat:@"0.%@",lastStr];
            NSString *last1=[NSString stringWithFormat:@"%.2f",[last floatValue]];
            
            if ([[[[last1 componentsSeparatedByString:@"."] lastObject] substringFromIndex:1] isEqualToString:@"0"]) {
                string=[NSString stringWithFormat:@"%@.%@",[arr firstObject],[[[last1 componentsSeparatedByString:@"."] lastObject] substringToIndex:1]];
            }else{
                string=[NSString stringWithFormat:@"%@.%@",[arr firstObject],[[last1 componentsSeparatedByString:@"."] lastObject]];
            }
            
            
        }else{
            if ([[lastStr substringFromIndex:1] isEqualToString:@"0"]) {
                string=[NSString stringWithFormat:@"%@.%@",[arr firstObject],[lastStr substringToIndex:1]];
            }else{
                string=str;
            }
            
        }
        
        
    }else{
        string=str;
        
    }
    //     WWLog(@"Helper str  %@  string   %@",str ,string)
    
    return string;
}
+ (BOOL)isCameraDenied
{
    AVAuthorizationStatus author = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (author == AVAuthorizationStatusRestricted || author == AVAuthorizationStatusDenied)
    {
        return YES;
    }
    return NO;
}

+ (BOOL)isCameraNotDetermined
{
    AVAuthorizationStatus author = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (author == AVAuthorizationStatusNotDetermined)
    {
        return YES;
    }
    return NO;
}

+ (BOOL)isPhotoAlbumDenied
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied)
    {
        return YES;
    }
    return NO;
}

+ (BOOL)isPhotoAlbumNotDetermined
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusNotDetermined)
    {
        return YES;
    }
    return NO;
}
+ (void)creatPhotoAlbumToSaveImage:(UIImage *)image;{
    
    PHFetchResult *assets = [self syncSaveImageWithPhotosImage:image];
    
    if (assets == nil)
    {
//        [GlobalContext showTextToast:@"图片保存失败" view:[UIApplication sharedApplication].keyWindow delay:2];
        return;
    }
    
    
    
    PHAssetCollection *assetCollection = [self getAssetCollectionWithAppNameAndCreateIfNo];
    if (assetCollection == nil) {
//        [GlobalContext showTextToast:@"相册创建失败" view:[UIApplication sharedApplication].keyWindow delay:2];;
        return;
    }
    //3 将刚才保存到相机胶卷的图片添加到自定义相册中 --- 保存带自定义相册--属于增的操作，需要在PHPhotoLibrary的block中进行
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        //--告诉系统，要操作哪个相册
        PHAssetCollectionChangeRequest *collectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        //--添加图片到自定义相册--追加--就不能成为封面了
        //        --[collectionChangeRequest addAssets:assets];
        //--插入图片到自定义相册--插入--可以成为封面
        [collectionChangeRequest insertAssets:assets atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:&error];
    
    
    if (error) {
//        [GlobalContext showTextToast:@"图片保存失败" view:[UIApplication sharedApplication].keyWindow delay:2];
        return;
    }
//    [GlobalContext showTextToast:@"图片保存成功" view:[UIApplication sharedApplication].keyWindow delay:2];;
}

/**拥有与 APP 同名的自定义相册--如果没有则创建*/
+(PHAssetCollection *)getAssetCollectionWithAppNameAndCreateIfNo
{
    //1 获取以 APP 的名称
    NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString *)kCFBundleNameKey];
    //2 获取与 APP 同名的自定义相册
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in collections) {
        //遍历
        if ([collection.localizedTitle isEqualToString:title]) {
            //找到了同名的自定义相册--返回
            return collection;
        }
    }
    
    //说明没有找到，需要创建
    NSError *error = nil;
    __block NSString *createID = nil; //用来获取创建好的相册
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        //发起了创建新相册的请求，并拿到ID，当前并没有创建成功，待创建成功后，通过 ID 来获取创建好的自定义相册
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
        createID = request.placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    if (error) {
        
        return nil;
    }else{
        
        //通过 ID 获取创建完成的相册 -- 是一个数组
        return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createID] options:nil].firstObject;
    }
    
}
/**同步方式保存图片到系统的相机胶卷中---返回的是当前保存成功后相册图片对象集合*/
+(PHFetchResult<PHAsset *> *)syncSaveImageWithPhotosImage:(UIImage *)image;
{
    //--1 创建 ID 这个参数可以获取到图片保存后的 asset对象
    __block NSString *createdAssetID = nil;
    
    //--2 保存图片
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        //----block 执行的时候还没有保存成功--获取占位图片的 id，通过 id 获取图片---同步
        createdAssetID = [PHAssetChangeRequest             creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
    } error:&error];
    
    //--3 如果失败，则返回空
    if (error) {
        return nil;
    }
    
    //--4 成功后，返回对象
    //获取保存到系统相册成功后的 asset 对象集合，并返回
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsWithLocalIdentifiers:@[createdAssetID] options:nil];
    return assets;
    
}

@end

